import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

enter_orise_router = APIRouter(prefix="/enterpriseBasic", tags=["危废数据字典查询接口"],
                               dependencies=[Depends(oauth2_scheme)])


class HazardousWasteDictionarySearch(PaginationBase):
    # 筛选条件
    site_no: Optional[str] = Field("", description="站点编号")
    enterpriseName: Optional[str] = Field("", description="企业名称(支持前缀匹配)")
    businessLicenseCode: Optional[str] = Field("", description="营业执照代码(支持前缀匹配)")
    industryCategoryCode: Optional[str] = Field("", description="行业类别代码")


@enter_orise_router.get("/list", summary="危废数据字典查询接口")
def list_enter_orise(search: HazardousWasteDictionarySearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from w_enterprise_basic where 1=1"
    if search.site_no != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.site_no
    if search.enterpriseName != "":
        sql = sql + " and enterprise_name like concat('%', :enterpriseName ,'%')"
        param["enterpriseName"] = search.enterpriseName
    if search.businessLicenseCode != "":
        sql = sql + " and business_license_code like concat('%', :businessLicenseCode ,'%')"
        param["businessLicenseCode"] = search.businessLicenseCode
    if search.industryCategoryCode != "":
        sql = sql + " and industry_category_code = :industryCategoryCode "
        param["industryCategoryCode"] = search.industryCategoryCode
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fsite_no,enterprise_id,enterprise_name,industry,industry_category_code,industry_category_type,province_id,"
    sql = sql + " city_id,street_id,owned_development_zone,business_license_code,business_license_code_file,enterprise_kind,"
    sql = sql + " address,longitude,latitude,link_man,phone,mobile,status,audit_status,enterprise_type,eia_annex_file,business_status,"
    sql = sql + " business_status_time,yewu_name,yewu_id,use_limit,open_status,create_at,create_by,update_at,update_by"
    sql = sql + " from w_enterprise_basic where 1=1"
    if search.site_no != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.site_no
    if search.enterpriseName != "":
        sql = sql + " and enterprise_name like concat('%', :enterpriseName ,'%')"
        param["enterpriseName"] = search.enterpriseName
    if search.businessLicenseCode != "":
        sql = sql + " and business_license_code like concat('%', :businessLicenseCode ,'%')"
        param["businessLicenseCode"] = search.businessLicenseCode
    if search.industryCategoryCode != "":
        sql = sql + " and industry_category_code = :industryCategoryCode "
        param["industryCategoryCode"] = search.industryCategoryCode
    sql = sql + " order by  enterprise_id "
    sql = sql + " limit :limit offset :offset "
    param["offset"] = search.offset
    param["limit"] = search.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fsiteNo'] = data[key][0]
        d1['enterpriseId'] = data[key][1]
        d1['enterpriseName'] = data[key][2]
        d1['industry'] = data[key][3]
        d1['industryCategoryCode'] = data[key][4]
        d1['industryCategoryType'] = data[key][5]
        d1['provinceId'] = data[key][6]
        d1['cityId'] = data[key][7]
        d1['streetId'] = data[key][8]
        d1['ownedDevelopmentZone'] = data[key][9]
        d1['businessLicenseCode'] = data[key][10]
        d1['businessLicenseCodeFile'] = data[key][11]
        d1['enterpriseKind'] = data[key][12]
        d1['address'] = data[key][13]
        d1['longitude'] = data[key][14]
        d1['latitude'] = data[key][15]
        d1['linkMan'] = data[key][16]
        d1['phone'] = data[key][17]
        d1['mobile'] = data[key][18]
        d1['status'] = data[key][19]
        d1['auditStatus'] = data[key][20]
        d1['enterprisetype'] = data[key][21]
        d1['eiaannexfile'] = data[key][22]
        d1['businessStatus'] = data[key][23]
        d1['businessStatusTime'] = data[key][24]
        d1['yewuName'] = data[key][25]
        d1['yewuId'] = data[key][26]
        d1['useLimit'] = data[key][27]
        d1['openStatus'] = data[key][28]
        d1['createAt'] = data[key][29]
        d1['createBy'] = data[key][30]
        d1['updateAt'] = data[key][31]
        d1['updateBy'] = data[key][32]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "limit": search.limit,
                 "page": search.pageIndex,
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)
